package cn.itsource.exam.conf;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1 放行 /login /logout /dfs /user/phoneRegister

        String uri = request.getRequestURI();

        //拦截
        String uToken = request.getHeader("U-TOKEN");
        if (StringUtils.isBlank(uToken)){
            writeNoUserError(response);
            return false;
        }
        Object user = request.getSession().getAttribute(uToken);
        if (user == null){
            writeNoUserError(response);
            return false;
        }
        return super.preHandle(request, response, handler);
    }

    private void writeNoUserError(HttpServletResponse response) {

        PrintWriter writer = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            writer = response.getWriter();
            writer.write("{\"success\":false,\"message\":\"noUser\"}");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer != null) {
                writer.close();
            }
        }
    }


}
